package com.raychi.demo.service;

import java.sql.Connection;
import java.sql.SQLException;

import com.raychi.demo.dao.TeacherDao;
import com.raychi.demo.entity.Teacher;
import com.raychi.demo.util.JdbcUtil;
import com.raychi.demo.util.SessionUtil;

public class TeacherService {
	private TeacherDao teacherDao;
	/**
	 * 通过id来查找教师
	 * @return 教师的表单
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public Teacher getTeacher() throws ClassNotFoundException, SQLException{
		Connection conn = null;
		Teacher teacher = null;
		try{
			conn = JdbcUtil.getConnection();
			teacher = teacherDao.getTeacherById(conn, SessionUtil.getTeacher().getId());
			conn.commit();
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
		return teacher;
	}
	
	/**
	 * 用户的登录 如果匹配到 session保存信息 
	 * @param username 页面输入的用户名
	 * @param password 页面输入的密码
	 * @return 找到result为true
	 */
	public boolean login (String username, String password) {
		Connection conn = null;
		Teacher teacher = null;
		boolean result = false;
		try{
			conn = JdbcUtil.getConnection();
			teacher = teacherDao.getTeacherByUsernameAndPassword(conn, username, password);
			if (teacher != null) {
				SessionUtil.setTeacherSession(teacher);
				result = true;
			}
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
		return result;
		
	}
	
	/**
	 * 注册时将没有相同用户名的用户存入数据库
	 * @param teacher 页面传入的注册时的用户名
	 * @return 成功返rsl为succ 失败 rsl为fail
	 */
	public String save(Teacher teacher){
		Connection conn = null;
		String rsl = "succ";
		
		try{
			conn = JdbcUtil.getConnection();
			int count = teacherDao.getCountTeacherByUsername(conn, teacher.getUsername());
			if (count > 0) {
				rsl = "fail";
			} else {
				teacherDao.save(teacher, conn);
				conn.commit();
			}
		}catch(Exception e){
			JdbcUtil.rollback(conn);
		}finally{
			JdbcUtil.closeConnection(conn);
		}
		return rsl;
	}
	

	
	public void setTeacherDao(TeacherDao teacherDao) {
		this.teacherDao = teacherDao;
	}
}
